#include <thread>
#include <unistd.h>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>

using namespace std;

void get_memory_by_pid(pid_t pid)
{
	FILE* fd;
	char line[1024] = {0};
	char virtual_filename[32] = {0};
	char vmrss_name[32] = {0};
	int vmrss_num = 0;
	sprintf(virtual_filename, "/proc/%d/status", pid);
	fd = fopen(virtual_filename, "r");
	if(fd == NULL) {
		cout << "open " << virtual_filename << " failed" << endl;
		exit(1);
	}

	// VmRSS line is uncertain
	while (fgets(line, 128, fd) != NULL)
	{
		if (strncmp(line, "VmRSS:", 6) == 0)
		{
			cout << "当前进程" << pid << "占用内存大小为：" <<  atoi(line + 6) << endl;
			break;
		}
	}
	fclose(fd);
	return;
}


void createVecEx(std::vector<std::string> &test)
{
	char str1[1024] = "hello,world";
	for (int i=0; i<1000; i++) {
		std::string	str2(str1);
		test.push_back(str2);
	}
}

void *createVec(void *args)
{
	pid_t id = getpid();
	std::vector<std::string> test;
	createVecEx(test);
	get_memory_by_pid(id);
	sleep(2);
	return 0;
}

int main() 
{
	pthread_t threads[5];
	for (int i=0; i<5; i++) {
		int rc = pthread_create(&threads[i], NULL, createVec, NULL);
		if (rc) {
			cout << "Failed to create pthread" << endl;
			exit(-1);
		}
		get_memory_by_pid(getpid());
	}
	sleep(2);
	cout << "---" << getpid() << endl;
	get_memory_by_pid(getpid());
	pthread_exit(NULL);

	return 0;
}
